package middlewares

import (
	"krm_pro/utils"

	"github.com/fatedier/beego/logs"
	"github.com/gin-gonic/gin"
)

type returnD struct {
	ReturnData
	status int
}
type ReturnData struct {
	Status  int    `json:"status"`
	Message string `json:"message"`
	Data    map[string]any
}

func NewReturnData(s1 int, s2 int, m string) (code int, obj any) {
	code = s1
	aa := make(map[string]interface{})
	aa["message"] = m
	aa["status"] = s2
	obj = aa
	return
}

func JwtCheck(r *gin.Context) {
	requestUrl := r.FullPath()
	if requestUrl == "/api/auth/login" || requestUrl == "/api/auth/logout" {
		logs.Debug(map[string]interface{}{"目前请求路径为": requestUrl}, "登录和退出不需要token验证")
		r.Next()
		return
	}
	tokenstring := r.Request.Header.Get("Authorization")
	if tokenstring == "" {
		// r.JSON(200, gin.H{
		// 	"status":  401,
		// 	"message": "请求未携带token,请登录后尝试",
		// })
		r.JSON(NewReturnData(200, 301, "请求未携带token,请登录后尝试"))
		r.Abort()
		return
	}
	claims, err := utils.ParseToken(tokenstring)
	if err != nil {
		r.JSON(200, gin.H{
			"status":  401,
			"message": "Token验证未通过",
		})
		r.Abort()
		return
	}
	r.Set("claims", claims)
	r.Next()
}
